<template>
	<view>
		<view class="top background-image">
		</view>
		<!-- <view class="top background-image" @click="gotoPage('/subPackTask/index')">
		</view> -->
		
		<view class="data-box" v-for="(menuItem,menuIndex) in menus" :key="menuIndex">
			<view class="cu-bar bg-white">
				<view class="action data-box-title">
					<text class="cuIcon-titles"></text> {{menuItem.meta.title}}
				</view>
			</view>
			<view class="model">
				<view class="">
					<u-grid :border="false" col="4" >
						<u-grid-item v-for="(item,index) in menuItem.children" :key="index" @click="gotoPage(item.component)">
							<u-avatar
								v-if="item.path == 'mysp'"
								:customStyle="{marginTop:'20rpx',borderRadius:'30%'}"
								:text="spCount"
								bgColor="#0087FC"
								shape="square"
								size="40"
								fontSize="20">
							</u-avatar>
							<u-icon
								v-else
								:customStyle="{paddingTop:20+'rpx'}"
								:name="item.meta.icon"
								size="40">
							</u-icon>
							<text class="grid-text">{{item.meta.title}}</text>
						</u-grid-item>
					</u-grid>
				</view>
			</view>
		</view>
		
		<!-- 弹出层：提示打卡成功 -->
		<clock-success
		:showDkSuc="showDkSuc"
		:beginDkTime="beginDkTime"
		:endDkTime="endDkTime"
		:isBeginDk="isBeginDk"
		:isEndDk="isEndDk"
		v-on:isShow='isShowSuc'
		></clock-success>
		
		<!-- 判断是否在距离内 -->
		<!-- <get-position  v-on:getMyPosition="getOwnerPosition"></get-position> -->
		
		<!-- 判断是否迟到 -->
		<view>
			<u-action-sheet
			round="10"
			:closeOnClickOverlay="true" 
			:closeOnClickAction="true"  
			title="迟到打卡备注" 
			:show="popupShow"
			@close="popupShow=false">
				<u-divider style="margin-top: -10rpx;"></u-divider>
				<view style="margin: 0 25rpx 25rpx 25rpx;text-align: left;">
					<text style="color: #000000;font-size: 32rpx;">备注(选填)</text>
					<u--input
					placeholder="请填写迟到原因"
					border="bottom"
					style="margin-bottom: 30rpx;"
					v-model="lateOrEarlyRemark"
					>
					</u--input>
					<u-button color="#FE8802" text="迟到打卡" @click="confirmDk()"></u-button>
				</view>
			</u-action-sheet>
		</view>
	</view>
</template>

<script>
	import { getSpCount } from '@/api/flow.js' 
	import getDateTime from '@/utils/getdateTime.js' //获取当天日期
	import { editDk, getDkInfo } from '@/api/kqdk.js'
	import { getDistance, compareTime, getNowTime } from '@/utils/dkTools.js' //
	import { strFormatHourTime, strFormatHourMSTime } from '@/utils/format.js'
	import clockSuccess from '@/components/clock-success/clock-success.vue'
	import { getConfigKey } from '@/api/config'
	import getPosition from '@/components/get-position/get-position.vue'
	import { getRouters, getInfo } from '@/api/login.js'
	export default {
		components:{ clockSuccess ,getPosition },
		data() {
			return {
				spCount:'',
				user:{},
				isload:true,
				currentNum:0,
				list:[],
				menus:[],
				todayDate:''  ,//今天的日期
				dkInfo:'',
				dkInfoId:'',
				isBeginDk: false,
				beginDkTime:'',
				isEndDk: false,
				endDkTime:'',
				showDkSuc: false,  //打卡是否成功(弹出成功弹框)
				distance: '',  //距离
				popupShow: false,
				lateOrEarlyRemark: '',  //迟到原因
				xbAutoDkTime: 0,
			}
		},
		onPullDownRefresh(){
			
		},
		created() {
			this.getTodayDkInfo()
		},
		onShow(){
			this.getSpNum()
			this.getInfoData()
			this.getRoutersData()
			var timeStr = getDateTime.dateTimeStr('y-m-d');
			this.todayDate = timeStr
			let dkTodayDate = uni.getStorageSync('getTodayDate')
			if( dkTodayDate && dkTodayDate == this.todayDate ){
				this.xbAutoDkTime = uni.getStorageSync('xbAutoDkTime')
			} else {
				uni.removeStorageSync('getTodayDate');
				uni.removeStorageSync('xbAutoDkTime');
			}
		},
		onLoad() {
			if (!this.hasLogin) {
				uni.reLaunch({
					url: '/pages/login/index'
				})
				return
			}
			// this.user = uni.getStorageSync("loginInfo").user
			// let routers = uni.getStorageSync("routers")
			// if(routers.length > 0){
			// 	this.menus = routers[0].children
			// }
			
		},
		onReachBottom() {
		    //触底后执行的方法，比如无限加载之类的
			
		},
		methods: {
			async getSpNum(){
				const { data } = await getSpCount();
				if(data.code == 200){
					this.spCount = String(data.data) 
				}
			},
			replaceSpecialChar(text) {
			  text = text.replace(/&quot;/g, '"');
			  text = text.replace(/&amp;/g, '&');
			  text = text.replace(/&lt;/g, '<');
			  text = text.replace(/&gt;/g, '>');
			  text = text.replace(/&nbsp;/g, ' ');
			  return text;
			},
			// 获取自己的位置：
			getOwnerPosition(){
				uni.getLocation({
					type: 'wgs84',
					success: (res) => {
						this.distance = getDistance(res.latitude, res.longitude, this.dkInfo.latitude,this.dkInfo.longitude)
						console.log('自动打卡距离distance1：',this.distance);
						if( Math.round(this.distance) <= Number(this.dkInfo.distance) ) {
							this.dkAuto()
						}else{
							let time = setTimeout(item => {
								this.getOwnerPosition()
								clearTimeout(time) 
							},2000)
						}
					}
				});
			},
			// 自动打卡
			// 获取当天打卡信息
			async getTodayDkInfo() {
				const { data } = await getDkInfo()
				if( data.code === 200 ) {
					this.dkInfo = data.data
					this.dkInfoId = this.dkInfo.id
					if( this.dkInfo.beginTime ) {
						this.isBeginDk = true
						this.beginDkTime = this.dkInfo.beginTime.slice(-8,-3)
					}
					if( this.dkInfo.endTime.slice(-8) != '00:00:00' ) {
						this.isEndDk = true
						this.endDkTime = this.dkInfo.endTime.slice(-8,-3)
					}
					this.getOwnerPosition()
				}
			}, 
			async dkAuto(){
				// 查询用户上班点
				let dateTime = this.todayDate + " " + getNowTime()
				uni.setStorageSync('getTodayDate',this.todayDate)
				if( this.isBeginDk == false ) {
					// 上班打卡
					const isLater = compareTime(this.dkInfo.kqStart.slice(-8), getNowTime(), 'sbDk')
					if( isLater == false ) {
						this.editDk(this.dkInfoId, dateTime, this.dkInfo.endTime, this.lateOrEarlyRemark, 'sbDk')
					}else{
						let isLateLong = compareTime( this.dkInfo.kqStartTime, getNowTime(), 'isLateLong')
						if( isLateLong == true ){
							this.popupShow = false
						}else {
							this.popupShow = true
						}
					}
				} else {
					// 下班打卡
					const isEarly = compareTime(getNowTime(), this.dkInfo.kqEnd.slice(-8), 'xbDk')
					if( isEarly == false && this.xbAutoDkTime != 2 ) {
						this.editDk(this.dkInfoId, this.dkInfo.beginTime, dateTime, this.lateOrEarlyRemark, 'xbDk')
					}
				}
			},
			// 迟到打卡
			confirmDk() {
				let dateTime = this.todayDate + " " + getNowTime()
				this.editDk(this.dkInfoId, dateTime, this.dkInfo.endTime, this.lateOrEarlyRemark, 'sbDk')
			},
			// 上下班打卡
			async editDk(id, sbDkTime, xbDkTime , remark, type){
				let commitContent = {id:id, beginTime:sbDkTime, endTime:xbDkTime, remark:remark }
				const { data } = await editDk(commitContent)
				if(data.code === 200 && type == 'sbDk') {
					this.popupShow = false
					this.isBeginDk = true
					this.beginDkTime = sbDkTime.slice(-8,-3)
					let time = setTimeout(item => {
						this.showDkSuc = true
						clearTimeout(time)      
					}, 500)
					this.startMP3()
				} else if(data.code === 200 && type == 'xbDk') {
					this.showDkSuc = true
					this.isEndDk = true
					this.endDkTime = xbDkTime.slice(-8,-3)
					uni.setStorageSync('xbAutoDkTime',2)
					this.startMP3()
				}
				this.closeDkSucAuto()
			},
			// 播放打卡铃声
			startMP3() {
				const innerAudioContext = uni.createInnerAudioContext();
				innerAudioContext.autoplay = true;
				innerAudioContext.src = 'https://www.zxsl.zxmap.cn/zxch-app/2023/05/09/be646e18316f42548f1333bd058f03fd.mp3';
				innerAudioContext.onPlay(() => {console.log('成功播放')});
			},
			closeDkSucAuto(){
				//设置五秒后弹窗自动关闭
				let time = setTimeout(item => {
					this.showDkSuc = false;
					clearTimeout(time)      
				}, 3000)
			},
			isShowSuc(index){
				this.showDkSuc = index
			},
			async getRoutersData(){
				const { data } = await getRouters();
				if(data.code === 200){
					if(data.data.length > 0){
						this.menus = data.data[0].children
					}
					uni.setStorageSync("routers", data.data)
				}
			},
			async getInfoData(){
				const { data } = await getInfo();
				if(data.code === 200){
					this.user = data.data.user
					uni.setStorageSync("loginInfo", data.data)
				}
			},
		},
		
	}
</script>

<style lang="scss">
	page{
		background-color: #f6f6f6;
		color: #333333;
	}
	
	.grid-text {
		font-size: 14px;
		color: #5b5d61;
		padding: 10rpx 0 20rpx 0rpx;
		/* #ifndef APP-PLUS */
		box-sizing: border-box;
		/* #endif */
	}
	
	.background-image{
		overflow: hidden;
		// padding: 0 30rpx;
		background: url("https://www.zxsl.zxmap.cn/zxch-app/2023/07/21/287c674fe2f0432fbd24ae1d3f790176.png") no-repeat center center;
		background-size: 80%;
		width: 100%;
		height: 160rpx;
	}
	
	.top{
		flex: auto;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		background-color: white;
	}
	
	.data-box{
		margin-top: 20rpx;
		background-color: #ffffff;
		/* box-shadow: 0px 0px 5px rgba(0,0,0,.1); */
		padding: 0rpx;
	}
	
	.data-box .cu-bar{
		border-bottom: solid 1px #f9f9f9;
	}
	
	.data-box-title{
		color: #333;
		font-size: 32rpx !important;
		font-weight: bold;
		text-overflow: -o-ellipsis-lastline;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		line-clamp: 2;
		-webkit-box-orient: vertical;
	}
	
	.cu-bar {
		display: flex;
		position: relative;
		align-items: center;
		min-height: 100rpx;
		justify-content: space-between;
	}
	
	.cu-bar .action {
		display: flex;
		align-items: center;
		height: 100%;
		justify-content: center;
		max-width: 100%;
	}
	
	.cuIcon-titles {
		display: inline-block;
		vertical-align: bottom;
		height: 40rpx;
		width: 10rpx;
		background: #0081FF;
		margin: 0 20rpx 0 25rpx;
		border-radius: 10rpx;
	}
	
	.model{
		padding: 10rpx 0;
		width: 100%;
	}
</style>